/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hxg.portmgr.core.oper.RemoteClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import util.StringUtils;

/**
 *
 * @author hxg
 */
public abstract class RemoteClientOper {

    String ip;
    int port;
    InputStream is = null;
    OutputStream os = null;
    Return returnMode = Return.CRLF;
    StringBuffer sb = new StringBuffer();

    public RemoteClientOper(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public Return getReturnMode() {
        return returnMode;
    }

    public void setReturnMode(Return returnMode) {
        this.returnMode = returnMode;
    }

    public void sendAndReturn(String str) throws IOException {
        os.write((str + returnMode.toString()).getBytes());
        os.flush();
    }

    public void send(byte[] bytes) throws IOException {
        os.write(bytes);
        os.flush();
    }

    protected void startReader() {
        Thread reader = new Thread() {

            //final StringBuilder sb = new StringBuilder();
            //ArrayList<Byte> bytes = new ArrayList();
            byte[] recvs = new byte[0];
            int size = 0;
            ArrayList<Byte> scanbuff = new ArrayList();

            @Override
            public void run() {
                while (is != null) {
                    try {
                        if (is != null && (size = is.available()) > 0) {
                            byte[] buff = new byte[size];
                            is.read(buff);
                            sb.append(new String(buff));
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(RemoteClientOper.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                }
            }
        };
        reader.setDaemon(true);
        reader.start();
    }

    public String getResult() {
        return StringUtils.VT100removeChar2(StringUtils.removeBS(sb.toString()));
    }

    public String getOriginalResult() {
        return sb.toString();
    }

    public abstract void init();

    public abstract void close();
}
